//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package com.openbravo.pos.admin;

import javax.swing.*;

import cn.ekuma.data.ui.swing.AbstractDAOJEditor;
import cn.ekuma.epos.datalogic.I_DataLogicAdmin;

import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.bean.Resource;

import java.awt.CardLayout;
import java.awt.Component;
import java.util.Properties;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.ComboBoxValModel;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.ImageUtils;
import com.openbravo.data.user.DirtyManager;
import com.openbravo.format.Formats;
import com.openbravo.bean.erp.OrderState;
import com.openbravo.pos.util.Base64Encoder;
import java.awt.Frame;
import java.io.ByteArrayOutputStream;
import org.jgraph.event.GraphSelectionEvent;
import org.jgraph.event.GraphSelectionListener;
import org.ofsm.creator.EventGraphEdge;
import org.ofsm.creator.StateDiagramManager;
import org.ofsm.creator.StateGraphCell;
import org.ofsm.creator.TransitionEditorDialog;
import org.ofsm.impl.FileFiniteStateMachineBaseModel;
import org.ofsm.impl.FileFiniteStateMachineModel;
import org.ofsm.impl.State;

/**
 *
 * @author adrianromero
 */
public class ResourcesView extends AbstractDAOJEditor<Resource> {
    
    private ComboBoxValModel m_ResourceModel;
    private FileFiniteStateMachineModel model ;
    private StateDiagramManager stateDiagramMgr;
        
    /** Creates new form ResourcesEditor */
    public ResourcesView(I_DataLogicAdmin dlAdmin,DirtyManager dirty) {
    	super(dirty);
        initComponents();
        m_ResourceModel = new ComboBoxValModel();
        m_ResourceModel.add(ResourceType.TEXT);
        m_ResourceModel.add(ResourceType.IMAGE);
        m_ResourceModel.add(ResourceType.BINARY);
        m_ResourceModel.add(ResourceType.STATE);
        m_jType.setModel(m_ResourceModel);
        
        m_jName.getDocument().addDocumentListener(dirty);
        m_jType.addActionListener(dirty);
        m_jText.getDocument().addDocumentListener(dirty);
        m_jImage.addPropertyChangeListener("image", dirty);
       
        model = new FileFiniteStateMachineModel();
        model.setSafeUnmarshallingMode(true);
        stateDiagramMgr = new StateDiagramManager(model, diagramGraph);

        diagramGraph.addGraphSelectionListener(new GraphSelectionListener() {
            @Override
                    public void valueChanged(GraphSelectionEvent e) {
                        diagramGraph_valueChanged(e);
                    }
        });
        writeValueEOF();        
    }

    public Component getComponent() {
        return this;
    }
    
    public void refresh() {
    }
    
    private void showView(String view) {
        CardLayout cl = (CardLayout)(m_jContainer.getLayout());
        cl.show(m_jContainer, view);  
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        m_jGroupType = new javax.swing.ButtonGroup();
        jPanel3 = new javax.swing.JPanel();
        m_jContainer = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        m_jText = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        m_jImage = new com.openbravo.data.gui.JImageEditor();
        jStateEdit = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jAddState = new javax.swing.JButton();
        jAddTransation = new javax.swing.JButton();
        btnRemoveTransition = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        diagramGraph = new org.jgraph.JGraph();
        jLabel2 = new javax.swing.JLabel();
        m_jName = new javax.swing.JTextField();
        m_jType = new javax.swing.JComboBox();

        jPanel3.setLayout(new java.awt.BorderLayout());

        m_jContainer.setLayout(new java.awt.CardLayout());

        m_jText.setFont(new java.awt.Font("DialogInput", 0, 12));
        jScrollPane1.setViewportView(m_jText);

        m_jContainer.add(jScrollPane1, "text");
        m_jContainer.add(jPanel1, "null");
        m_jContainer.add(m_jImage, "image");

        jStateEdit.setLayout(new java.awt.BorderLayout());

        jPanel4.setLayout(new java.awt.BorderLayout());

        jPanel5.setLayout(new javax.swing.BoxLayout(jPanel5, javax.swing.BoxLayout.LINE_AXIS));

        jAddState.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/ofsm/creator/images/layer--pencil.png"))); // NOI18N
        jAddState.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAddStateActionPerformed(evt);
            }
        });
        jPanel5.add(jAddState);

        jAddTransation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/ofsm/creator/images/layer-shape-curve.png"))); // NOI18N
        jAddTransation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAddTransationActionPerformed(evt);
            }
        });
        jPanel5.add(jAddTransation);

        btnRemoveTransition.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/ofsm/creator/images/cross-octagon-frame.png"))); // NOI18N
        btnRemoveTransition.setEnabled(false);
        btnRemoveTransition.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveTransitionActionPerformed(evt);
            }
        });
        jPanel5.add(btnRemoveTransition);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/ofsm/creator/images/node-delete-child.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel5.add(jButton1);

        jPanel4.add(jPanel5, java.awt.BorderLayout.NORTH);

        jPanel6.setLayout(new java.awt.BorderLayout());
        jPanel4.add(jPanel6, java.awt.BorderLayout.CENTER);
        jPanel4.add(diagramGraph, java.awt.BorderLayout.CENTER);

        jStateEdit.add(jPanel4, java.awt.BorderLayout.CENTER);

        m_jContainer.add(jStateEdit, "state");

        jPanel3.add(m_jContainer, java.awt.BorderLayout.CENTER);

        jLabel2.setText(AppLocal.getIntString("label.resname")); // NOI18N

        m_jType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jTypeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(m_jName, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(m_jType, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(m_jName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(m_jType, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void m_jTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jTypeActionPerformed

        ResourceType restype = (ResourceType) m_ResourceModel.getSelectedItem();
        if (restype == ResourceType.TEXT) {
            showView("text");
        } else if (restype == ResourceType.IMAGE) {
            showView("image");
        } else if (restype == ResourceType.BINARY) {
            showView("text");
        } else if (restype == ResourceType.STATE) {
            showView("state");
        } else {
            showView("null");
        }
      
    }//GEN-LAST:event_m_jTypeActionPerformed

    private void jAddStateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAddStateActionPerformed
        FileFiniteStateMachineBaseModel.StateInfo stateInfo = model.new StateInfo();
        State state = new State();
        state.setName(AppLocal.getIntString(OrderState.ORDERSTATE_Start));
        stateInfo.setState(state);
        model.addStateInfo(stateInfo);
        dirty.setDirty(true);
        updateVisualization();
}//GEN-LAST:event_jAddStateActionPerformed

    private void jAddTransationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAddTransationActionPerformed
        TransitionEditorDialog transDialog = new TransitionEditorDialog(model, (Frame)SwingUtilities.getWindowAncestor(this),"Add new transition",true);
        if(diagramGraph.getSelectionCount() > 0) {
            Object[] objs = diagramGraph.getSelectionCells();
            if(objs[0] instanceof StateGraphCell)
                transDialog.selectFromState((FileFiniteStateMachineModel.StateInfo)(((StateGraphCell)objs[0]).getUserObject()));
            if(objs.length > 1 &&objs[1]instanceof StateGraphCell) {
                transDialog.selectToState((FileFiniteStateMachineModel.StateInfo)(((StateGraphCell)objs[1]).getUserObject()));
            }
        }
        transDialog.setVisible(true);
        if(transDialog.isApproved()) {
            dirty.setDirty(true);
            updateVisualization();
        }
}//GEN-LAST:event_jAddTransationActionPerformed

    private void btnRemoveTransitionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveTransitionActionPerformed
        int result = JOptionPane.showConfirmDialog(this,"Are you sure you want to delete the transition?","Warning",JOptionPane.YES_NO_OPTION);
        if(result==JOptionPane.YES_OPTION) {
            Object obj=diagramGraph.getSelectionCell();
            if(obj instanceof EventGraphEdge){
                stateDiagramMgr.removeSelectedTransition();  
            } else if(obj instanceof StateGraphCell){
                stateDiagramMgr.removeSelectedState();
            }
            dirty.setDirty(true);
            updateVisualization();
        }
}//GEN-LAST:event_btnRemoveTransitionActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        FileFiniteStateMachineBaseModel.StateInfo stateInfo = model.new StateInfo();
        State state = new State();
        state.setName(AppLocal.getIntString(OrderState.ORDERSTATE_End));
        stateInfo.setState(state);
        model.addStateInfo(stateInfo);
        dirty.setDirty(true);
        updateVisualization();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void updateVisualization() {
        stateDiagramMgr.setupModel();
        diagramGraph.updateUI();
    }

    private void diagramGraph_valueChanged(GraphSelectionEvent e) {
        btnRemoveTransition.setEnabled(false);
        if(diagramGraph.getSelectionCount() == 1) {
            btnRemoveTransition.setEnabled(true);
        }
    }

     private byte[] createGrahpXmlModel() {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            model.marshal(output);
            return output.toByteArray();
        }
        catch(Exception ex) {
            JOptionPane.showMessageDialog(this,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
        }
        return null;
    }

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRemoveTransition;
    private org.jgraph.JGraph diagramGraph;
    private javax.swing.JButton jAddState;
    private javax.swing.JButton jAddTransation;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel jStateEdit;
    private javax.swing.JPanel m_jContainer;
    private javax.swing.ButtonGroup m_jGroupType;
    private com.openbravo.data.gui.JImageEditor m_jImage;
    private javax.swing.JTextField m_jName;
    private javax.swing.JTextArea m_jText;
    private javax.swing.JComboBox m_jType;
    // End of variables declaration//GEN-END:variables

	@Override
	public void activate() throws BasicException {

	}

	@Override
	public String getLogerString() {
				return null;
	}

	@Override
	public boolean isLogAble() {
		return false;
	}

	@Override
	public Resource createNew(Properties prop) {
		Resource newObj=new Resource();
		newObj.setResType(ResourceType.TEXT.getKey());
		return newObj;
	}

	@Override
	public void rebuild(Resource obj) throws BasicException {
		   ResourceType restype = (ResourceType) m_ResourceModel.getSelectedItem();
		    obj.setName(m_jName.getText());
		    obj.setResType(restype.getKey());
	        if (restype == ResourceType.TEXT) {
	        	obj.setContent((byte[]) Formats.BYTEA.parseValue(m_jText.getText()));
	        } else if (restype == ResourceType.IMAGE) {
	        	obj.setContent( ImageUtils.writeImage(m_jImage.getImage()));
	        } else if (restype == ResourceType.BINARY) {
	        	obj.setContent( Base64Encoder.decode(m_jText.getText()));
	        } else if (restype == ResourceType.STATE) {
	        	obj.setContent(createGrahpXmlModel());
	        } else {
	        	obj.setContent(null);
	        }
		
	}

	@Override
	public void updateUI(boolean editAble, int state) {
	        m_jName.setText(obj.getName());
	        m_ResourceModel.setSelectedKey(obj.getResType());
	        
	        ResourceType restype = (ResourceType) m_ResourceModel.getSelectedItem();
	        if (restype == ResourceType.TEXT) {
	            m_jText.setText(Formats.BYTEA.formatValue(obj.getContent()));
	            m_jText.setCaretPosition(0);
	            m_jImage.setImage(null);
	        } else if (restype == ResourceType.IMAGE) {
	            m_jText.setText(null);
	            m_jImage.setImage(ImageUtils.readImage(obj.getContent()));
	        } else if (restype == ResourceType.BINARY) {
	            m_jText.setText(obj.getContent() == null
	                     ? null: Base64Encoder.encodeChunked(obj.getContent()));
	            m_jText.setCaretPosition(0);
	            m_jImage.setImage(null);
	        } else if (restype == ResourceType.STATE) {
	            m_jText.setText(null);
	            m_jText.setCaretPosition(0);
	            m_jImage.setImage(null);
	            try {
	                model.unmarshal(new java.io.ByteArrayInputStream(obj.getContent()));
	            } catch (Exception ex) {
	                MessageInf msg = new MessageInf(MessageInf.SGN_NOTICE, AppLocal.getIntString("message.notStateMachineDOC"), ex);
	                msg.show(this);
	            }
	        } else {
	            m_jText.setText(null);
	            m_jImage.setImage(null);
	            model.init();
	        }
	        jStateEdit.setEnabled(true);
	        m_jName.setEnabled(true);
	        m_jType.setEnabled(true);
	        m_jText.setEnabled(true);
	        m_jImage.setEnabled(true);
	        updateVisualization();
		
	}

	@Override
	public Class getEditClass() {
		return Resource.class;
	}
    
}
